package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    public Result isfollow(Long id) {
        //查询数据库中是否有数据
        Integer count = this.lambdaQuery().eq(Follow::getFollowUserId, id)
                .eq(Follow::getUserId, UserHolder.getUser().getId()).count();
        return Result.ok(count>0);
    }

    public Result follow(Long id, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        if(isFollow){
            //关注
            Follow follow = new Follow();
            follow.setFollowUserId(id);
            follow.setUserId(userId);
            this.save(follow);
            stringRedisTemplate.opsForSet().add(RedisConstants.FOLLOW_COMMON+userId,id.toString());
        }else {
            //取消关注
            boolean remove = this.remove(new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, id));
            if (remove){
                stringRedisTemplate.opsForSet().remove(RedisConstants.FOLLOW_COMMON+userId,id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result common(Long id) {
        Long myId = UserHolder.getUser().getId();
        //从redis中取出共同关注 opsForSet().intersect取交集
        Set<String> set = stringRedisTemplate.opsForSet().intersect(RedisConstants.FOLLOW_COMMON + myId, RedisConstants.FOLLOW_COMMON + id);
        if (set==null||set.isEmpty()){
            return Result.ok();
        }
        List<String> ids = set.stream().map(String::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOS = BeanUtil.copyToList(users, UserDTO.class);
        return Result.ok(userDTOS);
    }
}
